﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Collections;
using System.Collections.ObjectModel;
using System.Text;

namespace Client_Revenue
{
    public partial class ContractSalesPerson : System.Web.UI.Page
    {
        #region properties & fields
        private SalesInfo _SalesInfo = new SalesInfo();
        
        private int _ContractId
        {
            get
            {
                if (this.ViewState["_ContractId"] == null)
                    return 0;

                return (int)this.ViewState["_ContractId"];
            }
            set { this.ViewState["_ContractId"] = value; }
        }
        private List<SalesInfo> iSalesInfo
        {
            get
            {
                if (this.ViewState["iSalesInfo"] == null)
                    return null;

                return (List<SalesInfo>)this.ViewState["iSalesInfo"];
            }
            set { this.ViewState["iSalesInfo"] = value; }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadPageData();
                LoadJScript();
            }
        }

        public void LoadPageData()
        {

            iSalesInfo = new List<SalesInfo>();
            using (var DE = new dominiumEntities())
            {
                //clients
                var theClients = (from c in DE.Clients
                                  join co in DE.Contracts on c.ClientId equals co.ClientId
                                  orderby c.ClientName ascending
                                  select new { c.ClientId, c.ClientName, co.ContractId }
                                 ).Distinct().ToList();

                ddClient.DataSource = theClients;
                ddClient.DataTextField = "ClientName";
                ddClient.DataValueField = "ClientId";
                ddClient.Items.Insert(0, new ListItem("Select Client", "0"));
                ddClient.SelectedIndex = 0;
                ddClient.DataBind();

                //Producers
                var theProducers = (from p in DE.People
                                    join t in DE.SalesTeams on p.PersonId equals t.PersonId
                                    orderby p.LastName
                                    select new
                                    {
                                        p.PersonId,
                                        FullName = p.FirstName + " " + p.LastName
                                    }).Distinct().ToList();


                //Producer
                chlProducers.Items.Clear();
                StringBuilder sb = new StringBuilder();

                //chlProducers.DataSource = theProducers;
                foreach (int id in theProducers.Select(p => p.PersonId))
                {
                    CheckBoxList list = new CheckBoxList();
                    ListItem cb = new ListItem();

                    cb.Text = theProducers.Where(x => x.PersonId == id).Select(s => s.FullName).FirstOrDefault();

                    sb.Append("readCheckBoxList('" + chlProducers.ClientID);
                    sb.Append("','" + hfProducerID.ClientID);
                    sb.Append("');");
                    cb.Attributes.Add("onclick", sb.ToString());
                    cb.Value = id.ToString();
                    chlProducers.Items.Add(cb);
                }

                chlProducers.DataBind();

                //SalesRoles
                var theSalesRoles = (from r in DE.SalesRoles
                                     select new
                                     {
                                         r.SalesRoleId,
                                         r.RoleName
                                     }).Distinct().ToList();

                ddProducerRole.DataSource = theSalesRoles;
                ddProducerRole.DataTextField = "RoleName";
                ddProducerRole.DataValueField = "SalesRoleId";
                ddProducerRole.SelectedIndex = 1;
                ddProducerRole.DataBind();
            }
        }

        protected void bnProdCommSubmit_Click(object sender, EventArgs e)
        {
            int SalesRoleId = Convert.ToInt32(ddProducerRole.SelectedValue);
            int ContractProducer;

            //get selected producers
            var selectedProducers = (from ListItem i in chlProducers.Items where i.Selected select i);
            //the last selection was
            if (selectedProducers.LastOrDefault().Value != null)
            {
                    ContractProducer = (Convert.ToInt32(selectedProducers.LastOrDefault().Value));
                    _SalesInfo.PersonId = ContractProducer;
            }
            //Add Sales Info
               
                _SalesInfo.SalesRoleId = SalesRoleId;
                _SalesInfo.Commission = Decimal.Parse(txtProdComm.Text);
                _SalesInfo.Fee = Decimal.Parse(txtProdFee.Text);
                _SalesInfo.ContractId = _ContractId;

                Decimal Zero = new Decimal(0);
                if (Decimal.Compare(Zero, Decimal.Parse(_SalesInfo.Fee.ToString())) != 0)
                {
                    _SalesInfo.RevenueTypeId = 1002;  // Consulting Fee
                }
                else
                {
                    _SalesInfo.RevenueTypeId = 1000;  // Commission
                }

                //Add to the List
                iSalesInfo.Add(_SalesInfo);
        }

        protected void ddClient_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (var DE = new dominiumEntities())
            {
                int _clientid = Convert.ToInt32(ddClient.SelectedValue);
                _ContractId = (DE.Contracts.Where(co => co.ClientId == _clientid).Select(co => co.ContractId).FirstOrDefault());
            }


        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {

            ClientScript.RegisterForEventValidation("chlProducers", "PersonId");
            ClientScript.RegisterForEventValidation("ddProducerRole", "SalesRoleId");
            ClientScript.RegisterForEventValidation("ddClient", "ClientId");
            ClientScript.RegisterForEventValidation("btnSave");
            this.EnsureChildControls();
            base.Render(writer);

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                using (var DE = new dominiumEntities())
                {
                    _SalesInfo.StartDate = DE.Contracts.Where(co => co.ContractId == _ContractId).Select(co => co.StartDate).FirstOrDefault();

                    //Add Contract Producers 
                    foreach (SalesInfo sales in iSalesInfo)
                    {
                        DE.AddContractsSalesPersonel(_ContractId, sales.PersonId, sales.SalesRoleId, sales.RevenueTypeId, sales.Commission, sales.Fee, _SalesInfo.StartDate);
                    }
                    lblMessages.Text = "Producers successfully saved";
                    ddClient.Items.Clear();
                    LoadPageData();
                }
            }
            catch(Exception ex)
            {
                lblMessages.Text = "Producers were not saved due to system error <br/><br/>" + ex.InnerException;
            }
        }

        //load the javascript
        internal void LoadJScript()
        {
            ClientScriptManager script = Page.ClientScript;
            //prevent duplicate script
            if (!script.IsStartupScriptRegistered(this.GetType(), "GetSelected.js"))
            {
                script.RegisterStartupScript(this.GetType(), "GetSelected.js",
                "<script type='text/javascript' src='" + ResolveUrl("~/Scripts/GetSelected.js") + "'></script>");
            }

            }
    }
}